package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.PermissionsDto;
import com.itheima.reggie.entity.Permissions;
import com.itheima.reggie.mapper.PermissionsMapper;
import com.itheima.reggie.service.PermissionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements PermissionsService {
    /**
     * 保存设置的权限信息，先删除，在添加
     * @param empId 被设置权限员工的id
     * @return
     */
    @Override
    public List<Permissions> userPermissions(Long empId) {
        //设置查询条件
        LambdaQueryWrapper<Permissions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(empId != null, Permissions::getEmployeeId, empId);
        //条件查询
        Permissions permissions = new Permissions();
        permissions.setEmployeeId(empId);
        List<Permissions> list = new ArrayList<>();
        //使用查找全部的方法，来找出该员工的权限，将其返回给前端进行数据回显
        if (this.list(queryWrapper) != null) {
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public String savePermissions(PermissionsDto permissionsDto) {
        //先删除之前的权限
        LambdaQueryWrapper<Permissions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permissions::getEmployeeId, permissionsDto.getEmpId());
        this.remove(queryWrapper);
        //获得存放 权限方法访问路径和访问形式 的集合
        List<String> permissions = permissionsDto.getPermissions();
        //遍历集合，获得每个 方法的访问形式和访问路径
        for (String permission : permissions) {
            //以空格 对该字符串进行切割 ，第一个是访问方式， 第二个是访问路径
            String[] strings = permission.split(" ");
            //将数据封装到实体类中
            Permissions per = new Permissions();
            per.setEmployeeId(permissionsDto.getEmpId());
            per.setMethodType(strings[0]);
            per.setUrl(strings[1]);
            //将数据保存到数据库中
            this.save(per);
        }
        return "修改权限成功";
    }
}
